// 用户姓名
let userName;
// 用户的id，连接到  /websocket/uid  的uri地址  uid作为唯一标识！！！
// let uid;
// 房间号
// let roomId;
//websocket对象
let ws;

// rtc连接列表
var pcList = [];

// ice stun服务器地址
const config = {
    iceServers: [
        {
            urls: [
                "stun:stun.l.google.com:19302",
                "stun:stun1.l.google.com:19302",
                "stun:stun2.l.google.com:19302",
                "stun:stun.l.google.com:19302?transport=udp",
            ],
        },
        {
            urls: "turn:xxx.com:3478", // 跨网段需要部署 turn 服务器
            credential: "xxx",
            username: "xxx",
        },
    ],
};

// offer 配置 开启视频 开启语音
const offerOptions = {
    offerToReceiveVideo: 1,
    offerToReceiveAudio: 1,
};

// 通话列表
const videoContainer = document.getElementById("videoContainer");
const audioContainer = document.getElementById("audioContainer");

/*连接到websocket服务器*/
function startConn() {

    uid = getQueryVariable("uid");
    userName = $("#userName").val();
    roomId = getQueryVariable("roomId");

    console.log("开始连接websocket服务器" + "wss://" + location.host + "/websocket/" + uid);
    ws = new WebSocket("wss://" + location.host + "/websocket/" + uid);

    // 向websocket服务器注册自己的uid
    ws.onopen = (evt) => {
        console.log("connent WebSocket is ok");
        const sendJson = JSON.stringify({
            type: "conn",
            uid: uid,
        });
        ws.send(sendJson); // 注册uid

        // 加入房间
        joinRoom();
    };

    ws.onmessage = (msg) => {
        const str = msg.data.toString();
        const json = JSON.parse(str);
        switch (json.type) {
            case "conn":
                console.log("连接成功");
                // userName.disabled = true;
                // startConn.disabled = true;
                // roomName.disabled = false;
                // joinRoom.disabled = false;
                // hangUp.disabled = false;
                break;
            case "room":
                // 返回房间内所有用户
                console.log("执行room指令");
                sendRoomUser(json.roomUserList, 0);
                break;
            case "signalOffer":
                // 收到信令Offer
                console.log("执行signalOffer指令");
                signalOffer(json);
                break;
            case "signalAnswer":
                // 收到信令Answer
                console.log("执行signalAnswer指令");
                signalAnswer(json);
                break;
            case "iceOffer":
                // 收到iceOffer
                console.log("执行iceOffer指令");
                addIceCandidates(json);
                break;
            case "close":
                // 收到房间内用户离开
                console.log("执行close指令");
                closeRoomUser(json);
            default:
                break;
        }
    };


}

// 时间戳转date格式
function getLocalTime(nS) {
    nS = nS.substring(0, 10);
    // console.log(nS);
    return new Date(parseInt(nS) * 1000).toLocaleString().replace(/:\d{1,2}$/, ' ');
}

/*加入房间*/
function joinRoom() {

    // console.debug("加入房间1")
    // 修改房主信息
    setCreatorInfo(roomId)
    // console.debug("加入房间2")

    // 调取摄像头
    const userConstraints = {
        video: true,
        audio: true,
    };
    // 设置媒体流
    const medias = navigator.mediaDevices.getUserMedia(userConstraints)

    medias
        .then(function (mediaStream) {
            localStream = mediaStream; // 本地视频流
            addUserItem(uid, localStream.id, localStream);// 添加视频框
            // addAudioItem(uid, localStream.id, localStream);
            console.log()
            const str = JSON.stringify({
                type: "room",
                roomId: roomId,
                streamId: localStream.id,
            });
            ws.send(str);
            //roomName.disabled = true;
            //joinRoom.disabled = true;
        })
        .catch(function (e) {
            console.log(JSON.stringify(e));
        });
}


// 创建WebRTC
function createWebRTC(userName, isOffer) {

    const pc = new RTCPeerConnection(config); // 创建 RTC 连接
    pcList.push({userName, pc});
    localStream.getTracks().forEach((track) => pc.addTrack(track, localStream)); // 添加本地视频流 track
    if (isOffer) {
        // 创建 Offer 请求
        pc.createOffer(offerOptions).then(function (offer) {
            pc.setLocalDescription(offer); // 设置本地 Offer 描述，（设置描述之后会触发ice事件）
            const str = JSON.stringify({type: "signalOffer", offer, userName});
            ws.send(str); // 发送 Offer 请求信令
        });
        // 监听 ice
        pc.addEventListener("icecandidate", function (event) {
            const iceCandidate = event.candidate;
            if (iceCandidate) {
                // 发送 iceOffer 请求
                const str = JSON.stringify({
                    type: "iceOffer",
                    iceCandidate,
                    userName,
                });
                ws.send(str);
            }
        });
    }
    return pc;
}

// 为每个房间用户创建RTCPeerConnection
function sendRoomUser(list, index) {
    createWebRTC(list[index], true);
    index++;
    if (list.length > index) {
        sendRoomUser(list, index);
    }
}

// 接收 Offer 请求信令
function signalOffer(json) {
    // console.log("接收到signalOffer", json);
    const {offer, sourceName, streamId} = json;//这里出现了问题！！！
    addUserItem(sourceName, streamId);
    // addAudioItem(sourceName, streamId);
    const pc = createWebRTC(sourceName);
    pc.setRemoteDescription(new RTCSessionDescription(offer)); // 设置远端描述
    // 创建 Answer 请求
    pc.createAnswer().then(function (answer) {
        pc.setLocalDescription(answer); // 设置本地 Answer 描述
        const str = JSON.stringify({
            type: "signalAnswer",
            answer,
            userName: sourceName,
        });
        ws.send(str); // 发送 Answer 请求信令
    });

    // 监听远端视频流
    pc.addEventListener("addstream", function (event) {
        document.getElementById(event.stream.id).srcObject = event.stream; // 播放远端视频流
    });

    // 监听 ice
    pc.addEventListener("icecandidate", function (event) {
        const iceCandidate = event.candidate;
        if (iceCandidate) {
            // 发送 iceOffer 请求
            const str = JSON.stringify({
                type: "iceOffer",
                iceCandidate,
                userName: sourceName,
            });
            ws.send(str);
        }
    });
}

// 接收 Answer 请求信令
function signalAnswer(json) {
    const {answer, sourceName, streamId} = json;
    addUserItem(sourceName, streamId);
    // addAudioItem(sourceName, streamId);
    const item = pcList.find((i) => i.userName === sourceName);
    if (item) {
        const {pc} = item;
        pc.setRemoteDescription(new RTCSessionDescription(answer)); // 设置远端描述
        // 监听远端视频流
        pc.addEventListener("addstream", function (event) {
            document.getElementById(event.stream.id).srcObject = event.stream;
        });
    }
}

// 接收ice并添加
function addIceCandidates(json) {
    const {iceCandidate, sourceName} = json;
    const item = pcList.find((i) => i.userName === sourceName);
    if (item) {
        const {pc} = item;
        pc.addIceCandidate(new RTCIceCandidate(iceCandidate));
    }
}

// 房间内用户离开
function closeRoomUser(json) {
    const {sourceName, streamId} = json;
    if (sourceName === uid) {
        //踢出的人是自己
        hangUp();
    } else {
        //踢出的是别人
        const index = pcList.findIndex((i) => i.userName === sourceName);
        if (index > -1) {
            pcList.splice(index, 1);
        }
        removeUserItem(streamId, sourceName);
    }
}

// 挂断
function hangUp() {
    // 隐藏音频图标
    document.getElementById("earphone").style.display = "none";

    // userName.disabled = false;
    // startConn.disabled = false;
    // roomName.disabled = true;
    // joinRoom.disabled = true;
    // hangUp.disabled = true;
    if (localStream) {
        localStream.getTracks().forEach((track) => track.stop());
        localStream = null;
    }
    pcList.forEach((element) => {
        element.pc.close();
        element.pc = null;
    });
    pcList.length = 0;
    if (ws) {
        ws.close();
        ws = null;
    }
    videoContainer.innerHTML = "";
    $(".memberList").empty();// 清空列表

    //重定位到主页
    window.location.href = "/views/index.html";
}

// 添加用户,就是将用户的图像框添加到页面里
function addUserItem(userName, mediaStreamId, src) {

    // TODO video的大小改小点 thanks

    // 将用户名字添加到房间用户中
    setMemberList(userName);
    // 将用户视频框添加到房间中
    const div = document.createElement("div");
    div.id = mediaStreamId + "_item";
    div.className = "video-item";
    div.style = "display: inline-block;"

    const div2=document.createElement("div")

    const video = document.createElement("video");
    video.id = mediaStreamId;
    video.className = "video-play";
    video.controls = true;
    video.autoplay = true;
    video.muted = true;
    video.webkitPlaysinline = true;
    src && (video.srcObject = src);

    div2.appendChild(video)
    div.appendChild(video)
    videoContainer.appendChild(div);

}

// 移除用户
function removeUserItem(streamId, rmUid) {
    videoContainer.removeChild(document.getElementById(streamId + "_item"));
    $("#uid_" + rmUid).empty();
}

// 连接socket
startConn()

